<?php

namespace Iwesen\Sem\Track\Advertisers;

class Jinritoutiao
{
    protected $api =  "https://ad.toutiao.com/track/activate/";

    public function callback($param)
    {
        $clickId = isset($param['clickid'])?$param['clickid']:null;
        $link = isset($param['link'])?$param['link']:null;
        if(!$clickId && !$link){
            throw new \Exception( 'clickid and link at least one is required!');
        }
        if(!isset($param['event_type']) || !$event_type = $param['event_type']){
            $event_type = config('sem-track.jinritoutiao.event_type');
            if(!$event_type){
                throw new \Exception( 'event_type is not a exist !');
            }
        }
        try {
            $time = time();
            if($link){
                $link = urlencode($link);
                $url = $this->api."?link={$link}&event_type={$event_type}&conv_time={$time}";
            }else{
                $url = $this->api."?callback={$clickId}&event_type={$event_type}&conv_time={$time}";
            }

            $result = (new Request())->_request($url);
            $data = json_decode($result,true);
            if($data['code']==0){
                return 'success';
            }
            return 'fail';
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        }
    }
}